package com.htthorizon.file.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.htthorizon.file.config.OSSConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.htthorizon.common.core.domain.R;
import com.htthorizon.common.core.utils.file.FileUtils;
import com.htthorizon.file.service.ISysFileService;
import com.htthorizon.system.api.domain.SysFile;

import java.net.URL;
import java.util.Date;

/**
 * 文件请求处理
 * 
 * @author mark
 */
@RestController
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 文件上传请求
     */
    @PostMapping("upload")
    public R<SysFile> upload(@RequestParam(value="documentfile",required=false)MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(file.getOriginalFilename());
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    @Autowired
    private OSSConfig ossConfig;
    @GetMapping("/getUrl")
    public R<SysFile> getUrl(@RequestParam("fileName") String fileName){
        //获取相关配置
        String bucketName = ossConfig.getBucketName();
        String endPoint = ossConfig.getEndPoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();

        //创建OSS对象
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 100);
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
        SysFile sysFile = new SysFile();
        sysFile.setName(fileName);
        sysFile.setUrl(url.toString());
        return R.ok(sysFile);
    }

    @RequestMapping(value = "/upload2", consumes = MediaType.MULTIPART_FORM_DATA_VALUE,method = RequestMethod.POST)
    public R<SysFile> upload2(@RequestPart(value = "file") MultipartFile file){
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile2(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }

    }
}